import java.util.Random;

class Solution {
    public int[] smallestK(int[] nums, int k) {
        qsort(nums, 0, nums.length - 1, k);
        int[] ret = new int[k];
        for (int i = 0; i < k; i++) {
            ret[i] = nums[i];
        }
        return ret;
    }

    private void qsort(int[] nums, int l, int r, int k) {
        if (l >= r){
            return;
        }
        //首先对数组进行排序
        //选取基准元素
        int key = nums[new Random().nextInt(r - l + 1) + l];
        int left = l - 1, right = r + 1, i = l;
        while (i < right) {
            if (nums[i] < key) {
                swap(nums, ++left, i++);
            } else if (nums[i] == key) {
                i++;
            } else {
                swap(nums, --right, i);
            }
        }


        //分类讨论
        int a = left - l + 1, b = right - left - 1;
        if (a > k) {
            qsort(nums, l, left, k);
        } else if (a + b >= k) {
            return;
        } else {
            qsort(nums, right, r, k - a - b);
        }
    }

    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}


public class Test01 {

}
